package com.example.testapplication.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    // 在Serice销毁时调用
    @Override
    public void onDestroy() {
        Log.i("Service:","service已停止");
        super.onDestroy();
    }
    // service创建时被调用
    @Override
    public void onCreate() {
        Log.i("Service:","service已创建");
        super.onCreate();
    }
    // 每次启动Service时调用
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("Service:","Service已启动");
                // 模拟一段耗时任务
                long endTime = System.currentTimeMillis()+ 5 *1000;
                while (System.currentTimeMillis() < endTime){
                    synchronized (this){
                        try {
                            wait(endTime -System.currentTimeMillis());
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }
                stopSelf(); // 停止Service
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
}